header undefined responseJSON Alamofire 2.0和Swift 2.0

时间:2015-10-08 21:54:38

标签: ios swift alamofire

使用swift 2.0 Xcode 7和Alamofire 2.0,我想知道如何使用正确的HTTPAdditionalHeaders用法更新代码,在更新到2.0之前,此管理器会话配置工作正常但现在API给了我一个坏的请求由于未定义的标头。 ¿我该如何解决? ¿是否可以在ApiClient中维护alamoFireManager会话配置HTTPAdditionalHeaders?

ApiClient.swift

class ApiClient {

 // User token
  var oAuthToken = "R0Fh65G4MjCcD18OsiTcPIfHxohFIzFhapuWNFSBhX2conQ1e+3vlv0XrJQVcw7fRg=="

  var mainService:      MainService

  init() {

    let alamoFireManager = Manager.sharedInstance

    alamoFireManager.session.configuration.HTTPAdditionalHeaders = [
      "Authorization": "Bearer \(oAuthToken)"
    ]

   // override the default challenge behavior in Alamofire using the SessionDelegate override closures.
   //an example of how you can allow Alamofire to accept invalid certificates:

    alamoFireManager.delegate.sessionDidReceiveChallenge = { session, challenge in
      var disposition: NSURLSessionAuthChallengeDisposition = .PerformDefaultHandling
      var credential: NSURLCredential?

      if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
        disposition = NSURLSessionAuthChallengeDisposition.UseCredential
        credential = NSURLCredential(forTrust: challenge.protectionSpace.serverTrust!)
      } else {
        if challenge.previousFailureCount > 0 {
          disposition = .CancelAuthenticationChallenge
        } else {
          credential = alamoFireManager.session.configuration.URLCredentialStorage?.defaultCredentialForProtectionSpace(challenge.protectionSpace)

          if credential != nil {
            disposition = .UseCredential
          }
        }
      }

      return (disposition, credential)
    }

    mainService      = MainService()
  }

}

MainService.swift

struct MainService {

  enum Router: URLRequestConvertible {

    static let baseURLString = "https://api.test.com/v1"

    case GetList([String: AnyObject])
    case GetById(String)

    var method: Alamofire.Method {
      switch self {
      case .GetList:
        return .GET
      case .GetById:
        return .GET
      case .Add:
        return .POST
      case .Update:
        return .PUT
      case .Delete:
        return .DELETE
      }
    }

    var path: String {
      switch self {
      case .GetList:
        return "/flyers"
      case .GetById(let id):
        return "/flyers/\(id)"
      case .Add:
        return "/flyers"
      case .Update(let id, _):
        return "/flyers/\(id)"
      case .Delete(let id):
        return "/flyers/\(id)"
      }
    }

    var URLRequest: NSMutableURLRequest {
      let URL = NSURL(string: Router.baseURLString)!
      let mutableURLRequest = NSMutableURLRequest(URL: URL.URLByAppendingPathComponent(path))
      mutableURLRequest.HTTPMethod = method.rawValue

      switch self {
      case .GetList(let parameters):
        return Alamofire.ParameterEncoding.URL.encode(mutableURLRequest, parameters: parameters).0
      case .Add(let parameters):
        return Alamofire.ParameterEncoding.JSON.encode(mutableURLRequest, parameters: parameters).0
      case .Update(_, let parameters):
        return Alamofire.ParameterEncoding.JSON.encode(mutableURLRequest, parameters: parameters).0
      default:
        return mutableURLRequest
      }
    }
  }

  func getList(completionHandler: ([Flyer]?, NSError?) -> ()) {

    Alamofire.request(Router.GetList(["skip": Test().getSkip(), "total":Test().getTotal()])).responseJSON { (request, response, result) in

      switch result {
      case .Success(let data):
        let json = JSON("Request success---------------------\(data)")
        print(json)
      case .Failure(_, let error):
        print("Request failed with error: \(error)")
      }

    }
  }

}

结果

Request success---------------------{
    code = "BAD_REQUEST";
    message = "Bad request";
    status = 400;
}

1 个答案:

答案 0 :(得分:1)

您必须将Authorization标头附加到实际的网址请求中。 Apple从未支持您尝试修改sharedInstance配置标头的方式。在iOS 9中,他们最终将行为与文档内联。在将配置应用于URL会话后,它们会忽略在配置上设置的标头。因此,您需要创建自己的自定义URL会话配置并在创建URL会话之前设置自定义标头,或者在Authorization标头的情况下,您需要将其直接附加到请求本身。< / p>

在您的路由器中,您应该在获取列表之前将Authorization标头附加到mutableURLRequest。这将解决您的问题。您必须弄清楚如何重构逻辑以使oAuthToken可以访问Router。我会考虑将其设为static var oAuthToken,以便您可以使用APIClient.oAuthToken轻松访问该值。