Alamofire背景服务,全球经理? 全球授权标题?

谁能告诉我如何正确使用Alamofire后台服务?

我的尝试是:

登录视图控制器

// Create a global variable for the manager var manager = Alamofire.Manager() var configuration = NSURLSessionConfiguration() class LoginViewController: UIViewController { // set the configuration for the manager configuration = NSURLSessionConfiguration.backgroundSessionConfigurationWithIdentifier("com.xxx.app.backgroundService") configuration.sharedContainerIdentifier = "com.xxx.app.backgroundService" } 

现在创建我的登录尝试,成功后转到MainViewController并在此处执行更多请求。

  manager.request(.POST, "\(serviceUrl)public/service/authenticate", parameters: ["email": txtEmail.text!, "password": txtPassword.text!]) { ...... } 

我得到了所有请求的令牌,所以生病添加到我的全局配置:

 class MainViewController: UIViewController { if let token: AnyObject = NSUserDefaults.standardUserDefaults().objectForKey("token") { configuration.HTTPAdditionalHeaders = ["Authorization": "Bearer \(token)"] manager = Alamofire.Manager(configuration: configuration) } } 

但是现在当退出登录并再次登录时 – 生病了以下错误:

 Warning: A background URLSession with identifier xxx.xxx.app.backgroundService already exists! 

应用程序崩溃:

 *** Terminating app due to uncaught exception 'NSGenericException', reason: 'Task created in a session that has been invalidated' *** First throw call stack: 

所以我真的不知道如何使用后台服务来获得以下结果:

在登录尝试时,我不需要添加身份validation标头。 但是,我想将它添加到每个请求中。 所有请求都应作为后台服务运行。

任何人都可以帮助我,如何以正确的方式解决这个问题? 提前致谢!

你有很多问题。 首先,您需要将configuration对象传递给Manager初始化程序。 否则,您不在Manager实例中使用基础URL会话的configuration

第二个问题是,在将配置应用于Manager实例后,不应在配置上设置标头值。 Apple文档专门称之为。 我们也在我们的自述文件中说出来。 如果您需要处理授权令牌,则需要将它们作为附加到实际请求的标头传递。


更新#1

这是一个小例子,展示了如何创建可以全局使用的Manager实例。

 class NetworkManager { var authToken = "1234" // You'll need to update this as necessary let manager: Manager = { let configuration: NSURLSessionConfiguration = { let identifier = "com.company.app.background-session" let configuration = NSURLSessionConfiguration.backgroundSessionConfigurationWithIdentifier(identifier) return configuration }() return Manager(configuration: configuration) }() static let sharedInstance = NetworkManager() } class ExampleClass { func startNetworkRequest() { let headers = ["Authorization": NetworkManager.sharedInstance.authToken] NetworkManager.sharedInstance.manager.request(.GET, "https://httpbin.org/get", headers: headers) .responseJSON { response in debugPrint(response) } } } 

您仍然需要了解如何在authToken到期时更新它,但这显示了如何在整个代码库中使用您的manager实例。