Alamofire后台服务,全球经理?全球授权头? [英] Alamofire Background Service, Global Manager? Global Authorisation Header?

查看:85
本文介绍了Alamofire后台服务,全球经理?全球授权头?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以告诉我如何正确使用Alamofire后台服务吗?

Can anyone tell me how to use the Alamofire background service correctly?

我的尝试是:

登录视图控制器

// 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并在此处执行更多请求。

Now creating my login attempt, when successful go to the MainViewController and do here some more Requests.

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

在这里,我为所有请求获取了令牌,因此,请将该令牌添加到我的全局配置中:

Here ill get my token for all requests, so ill add the to my global configuration:

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

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

But now when ill logout and login again - ill get the following errors:

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

应用崩溃,并显示以下信息:

And the app crashes with:

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

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

So i really dont know how do use the background-service to get the following result:

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

At login attempt, i dont need to add an authentication header. But then, i would like to add it to every request. All requests should run as background service.

有人可以帮助我,如何以正确的方式解决问题?

Can anyone help me out, how to solve that in a correct way? Thanks in advance!

推荐答案

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

You have multiple problems. The first is that you need to pass the configuration object into the Manager initializer. Otherwise you are not using the configuration for the underlying URL session in the Manager instance.

第二个问题是,在将配置应用于 Manager 实例后,不应在配置上设置标头值。苹果文档专门对此进行了说明。我们还在自述文件中对此进行了说明。如果需要处理授权令牌,则需要将它们作为附加到实际请求的标头传递。

The second issue is that you should NOT set header values on a configuration after it has been applied to a Manager instance. The Apple docs specifically call this out. We also call this out in our README. If you need to deal with authorization tokens, you need to pass them as a header attached to the actual request.

这是一个小示例,展示了如何创建 Manager 实例,该实例可在全球范围内使用。

Here's a small example showing how you could create a Manager instance that could be used globally.

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 过期后如何更新,但这显示了一种如何使用<整个代码库中的code> manager 实例。

You'll still need to work out how to update the authToken when it expires, but this shows one way how you could use your manager instance throughout your codebase.

这篇关于Alamofire后台服务,全球经理?全球授权头?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆