我正在尝试建立一个类来管理我的项目的网络调用。到目前为止,我的意思是在全局范围内处理错误,一切都很好。我创建了两个函数;用于发布请求postRequest(:_)和用于获取请求getRequests(:_)。 Datamaker函数返回URL,参数, header 等数据,dataparser函数解析响应数据,最后是解决错误的函数errorHandler()

当我调用请求函数之一时,我提供了一个参数来帮助函数应发出的请求。在该函数中,它首先调用数据制作者以获取数据,然后使用Alamofire发出请求,最后,如果请求成功,则调用dataparser和onSuccess(data:)闭包;否则,调用errorHandler(statusCode:)onFailure(message:)闭包。

我在errorHandler中放置了一个开关块,并为其参数指定了statusCode。在case 401中,我叫Token().refresh(),在它的完成中叫errorHanlder的完成。在postRequest/errorHandler的完成块中,我再次使用相同的参数调用了postRequest。没用我不知道为什么,它每次都陷入无限循环并连续发出请求。

因此,我决定尝试cnoonAuthorizationManager类(可以在此链接中找到; Alamofire : How to handle errors globally)。我做了一些更改(添加了新参数作为 header ,并将NetworkSuccessHandler的类型更改为NSData)。这是新表格:

public class AuthorizationManager: Manager {
    public typealias NetworkSuccessHandler = (NSData?) -> Void
    public typealias NetworkFailureHandler = (NSHTTPURLResponse?, AnyObject?, NSError) -> Void

    private typealias CachedTask = (NSHTTPURLResponse?, AnyObject?, NSError?) -> Void

    private var cachedTasks = Array<CachedTask>()
    private var isRefreshing = false

    public func startRequest(
        method method: Alamofire.Method,
        URLString: URLStringConvertible,
        parameters: [String: AnyObject]?,
        encoding: ParameterEncoding,
        headers: [String:String]?,
        success: NetworkSuccessHandler?,
        failure: NetworkFailureHandler?) -> Request?
        {
            let cachedTask: CachedTask = { [weak self] URLResponse, data, error in
                guard let strongSelf = self else { return }

                if let error = error {
                    failure?(URLResponse, data, error)
                } else {
                    strongSelf.startRequest(
                        method: method,
                        URLString: URLString,
                        parameters: parameters,
                        encoding: encoding,
                        headers:  headers,
                        success: success,
                        failure: failure
                    )
                }
            }

            if self.isRefreshing {
                self.cachedTasks.append(cachedTask)
                return nil
            }

            // Append your auth tokens here to your parameters

            let request = self.request(method, URLString, parameters: parameters, encoding: encoding, headers:  headers)

            request.response { [weak self] request, response, data, error in
                guard let strongSelf = self else { return }

                if let response = response where response.statusCode == 401 {
                    strongSelf.cachedTasks.append(cachedTask)
                    strongSelf.refreshTokens()
                    return
                }

                if let error = error {
                    failure?(response, data, error)
                } else {
                    success?(data)
                }
            }

            return request
    }

    func refreshTokens() {
        self.isRefreshing = true

            // Make the refresh call and run the following in the success closure to restart the cached tasks
        Token().refresh { () -> () in
            let cachedTaskCopy = self.cachedTasks
            self.cachedTasks.removeAll()
            cachedTaskCopy.map { $0(nil, nil, nil) }
            self.isRefreshing = false
        }
    }
}

用我的postRequest调用它,例如:
func postRequest(requestType: postRequestType, additionalParameters: [String]?, onSuccess: onSuccessRequest = {_ in }, onFailure: onFailureRequest = {_ in }){
    print("post")
    let requestData = returnStaticDataForPostRequest(requestType, additionalParameters: additionalParameters)
    let Manager = AuthorizationManager()
    Manager.startRequest(method: .POST, URLString: requestData.0, parameters: requestData.2, encoding: requestData.3, headers: requestData.1, success: { (data) -> Void in
        print("Manager")
        let json = JSON(data: data!)
        print(json)
        dataParserForPostRequests(json, parseForWhat: requestType)
        onSuccess(json: json)
        }) { (response, message, error) -> Void in
            print(error)
    }

}

并在postRequests中使用ViewController:
postRequest(.LOGIN, additionalParameters: ["asdasd", "asdasd"], onSuccess: { (json) -> () in
            print(">>>login_try_succeeded")
            self.performSegueWithIdentifier("LoginToMain", sender: self)
            }) { (errorCode) -> () in
            print(">>>login_try_failed(\(errorCode))")
        }

这是当前状态。当我运行代码并尝试登录AuthorizationManager时不起作用。它只是打印;
post

最后,我不知道它是否相关,但是此行有黄色警告:
cachedTaskCopy.map { $0(nil, nil, nil) }

"Result of call to 'map' is unused"
综上所述,我需要弄清楚如何处理401,并且我知道如何以与此不同的方式使用AuthorizationManager

编辑:

我尝试直接从ViewController运行此代码,但它根本不起作用。就像代码是不可见的。
AuthorizationManager().startRequest(method: .POST, URLString: NSURL(string: "http://server.url/token")!, parameters: ["":""], encoding: .JSON,headers: ["":""], success: { (data) -> Void in
            print(data)
            }) { (response, data, error) -> Void in
                print(error)
                print("asdasd")
        }

最佳答案

可能是您的AuthorizationManager在初次尝试发送请求后仍未保留。

通常,避免单例模式是一个好习惯,但这并不是一个坏情况:

public class AuthorizationManager: Manager {
    static let shared = AuthorizationManager()
    // ...the rest of your class
}

并且在调用您的请求时,请使用此单例实例,而不是像实例化一个新的AuthorizationManager
AuthorizationManager.shared.startRequest(method: .POST, ...etc...

我猜这可能是问题所在,因为在两种情况下都创建AuthorizationManager时,没有任何东西可以有效地保留该对象。可以创建管理器,运行请求,然后在cachedTask甚至完成处理之前将其释放,在这种情况下,您的guard let strongSelf = self else { return }将简单地返回而无需运行任何完成或cachedTasks。

希望有帮助。如果这是问题所在,那么单例解决方案应该非常简单。

10-04 21:20