Help us understand the problem. What is going on with this article?

[Swift] AlamofireのSessionDelegateを受け取る

More than 3 years have passed since last update.

SwiftのAlamofireを使用してのSSL通信の認証に少しはまったので備忘録。
※基本的な使い方は、他の人を参照下さい。
※この方法が正しいのかは分かりませんが、とりあえず成功はしました。


Objectice-C時代の<-(void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge>をAlamofireで受け取れればと、
いろいろ調べたり、Alamofireのコードをちょっと調べたりして、

AlamofireのSessionDelegateクラスにある (NSURLSessionAuthChallengeDisposition, NSURLCredential!))?>が受け取れるようになれば実現できそう。

このSessionDelegateクラスは、Alamofireのinitにて生成されていたので、以下の形で受け取るようにしました。

var alamoManger: Manager!
alamoManger = Manager(configuration: configuration)
let delegate: Manager.SessionDelegate = alamoManger.delegate

// HTTPS Authentication
delegate.sessionDidReceiveChallenge = { (session: NSURLSession!, challenge: NSURLAuthenticationChallenge) in
    return (.UseCredential, self.createSSLCertificate(challenge)! )
}

NSURLCredentialを生成するメソッド

func createSSLCertificate(challenge: NSURLAuthenticationChallenge) -> NSURLCredential! {

    if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodHTTPBasic
        || challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodHTTPDigest{
        // Basic認証
    }
    else {
        if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
            // SSL通信
        }
    }
}

リクエストする時はpublicクラスのAlamofireではなく、生成したManagerクラスをして行います。

alamoManger
    .request(.POST, url, parameters: parameters)
    .responseJSON({(request, response, data, error) in
    )

とりあえず、このコードで成功はしたのですが、何か間違っていたら教えて下さい。

Why do not you register as a user and use Qiita more conveniently?
  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
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  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