使用 RestKit 和 Swift 全局处理 401 响应

Global handling of 401 Responses with RestKit and Swift

我目前正在开发使用 Swift 开发的 iOS 应用程序。对于 REST 调用,我使用的是 RestKit 框架。

我项目的下一阶段是开始对服务使用身份验证。我遇到的一个问题是处理来自服务的 401(未验证)响应。在所有这些情况下,我想显示一个登录页面。我想避免多次执行此错误处理。

我遵循了 http://blog.higgsboson.tk/2013/09/03/global-request-management-with-restkit/ 上的教程。但是,这是在 Objective-C 中,我想做一些稍微不同的事情。

因此,我想构建一个 class 来扩展教程中的 RKObjectRequestOperation,但使用 Swift。当我收到错误

时,我遇到了一个问题

Overriding method with selector 'setCompletionBlockWithSuccess:failure:' has incompatible type '((RKObjectRequestOperation, RKMappingResult) -> Void (RKObjectRequestOperation, NSError) -> Void) -> Void'

我对此有点困惑,所以希望有人能提供帮助。失败方法的代码如下。

class CustomRequestOperation : RKObjectRequestOperation {
    func setCompletionBlockWithSuccess(success: (operation: RKObjectRequestOperation, mappingResult: RKMappingResult) -> Void, failure: (operation: RKObjectRequestOperation, error: NSError) -> Void) -> Void {

    }
}

任何人都可以指出我的方法签名有什么问题吗?

您正在重写该方法,因此如果您开始键入方法名称并转义,您可以 Xcode 为您添加签名。

应该是

func setCompletionBlockWithSuccess(success: (operation: RKObjectRequestOperation, mappingResult: RKMappingResult) -> Void, failure: (operation: RKObjectRequestOperation, error: NSError) -> Void) {

(您正在添加超类方法中不存在的 return 规范)

这是 swift 中的完整 class...

class CustomRKObjectRequestOperation : RKObjectRequestOperation
{

    override func setCompletionBlockWithSuccess(success: ((RKObjectRequestOperation!, RKMappingResult!) -> Void)!, failure: ((RKObjectRequestOperation!, NSError!) -> Void)!) {


        super.setCompletionBlockWithSuccess({ (operation, RKMappingResult mappingResult) -> Void in

            if ((success) != nil) {
                success(operation, mappingResult);
            }

            }, failure: { (RKObjectRequestOperation operation, NSError error) -> Void in

                NSNotificationCenter.defaultCenter().postNotificationName("connectionFailure",object:operation)

                if ((failure) != nil) {
                    failure(operation, error);
                }

        })

    }
}

应用委托

注册通知

NSNotificationCenter.defaultCenter().addObserver(self, selector:"connectionFailedWithOperation:",name:"connectionFailure", object:nil) 

func connectionFailedWithOperation(notification: NSNotification  ){


    let operation = notification.object as! RKObjectRequestOperation?;
    if ((operation) != nil) {

        let statusCode = operation!.HTTPRequestOperation.response.statusCode;

        if (statusCode == 401) {

            // log user out


        }
    }
}