LoginSignup
6
5

More than 5 years have passed since last update.

APIKit のアダプタの作り方

Posted at

APIKit を使った通信処理で URLSessionTaskDelegate を扱いたい場合には URLSessionAdapter を自前で用意すれば良い。

  • URLSessionAdapter のサブクラスを用意する
  • URLSessionDelegate, URLSessionTaskDelegate, URLSessionDataDelegate を実装する(任意)
  • Session のインスタンスを初期化する際にアダプタを指定する
class MySessionAdapter: URLSessionAdapter {

    override func createTask(with URLRequest: URLRequest, handler: @escaping (Data?, URLResponse?, Error?) -> Swift.Void) -> SessionTask {
        let task = super.createTask(with: URLRequest, handler: handler)
        return task
    }

    override func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
        super.urlSession(session, dataTask: dataTask, didReceive: data)
    }

    override func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
        super.urlSession(session, task: task, didCompleteWithError: error)
    }

}
使い方
let sessionAdapter = MySessionAdapter.init(configuration: URLSessionConfiguration.default)
let session = Session(adapter: sessionAdapter)
let sessionTask = session.send(request) {}
6
5
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
6
5