LoginSignup
16

More than 5 years have passed since last update.

Alamofireのrequestにtimeoutを設定する

Last updated at Posted at 2015-11-27

環境

  • Xcode: 7.1
  • Alamofire: 3.1.3

Problem

  • Alamofireのhttpリクエストにtimeoutを設定したい
  • googleで検索した方法でtimeoutを設定すると、「Error Domain=NSURLErrorDomain Code=-999 "cancelled"」というエラーが発生する

Solution

いろいろ試した結果、以下のコードでtimeoutが設定されることを確認した。
どうして他の方法だとcancelledになるのかまでは調べてない。

// ApiClient.swift:

class ApiManager {
  static let sharedInstance: Manager = {
    let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
    configuration.HTTPAdditionalHeaders = Manager.defaultHTTPHeaders
    configuration.timeoutIntervalForRequest = 10
    return Manager(configuration: configuration)
  }()
}

class ApiClient {
  static func hoge() {
    ...
    let manager = ApiManager.sharedInstance
    request = manager.request(method, urlString, headers: headers, parameters: parameters)
    request.validate(statusCode: 200..<500)
      .responseJSON  { response in
        ....
      }
    }
  }
}

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
16