iosfacebookswiftnssecurecoding

NSSecureCoding in Swift (Facebook SDK)


I am trying to translate a Objective-C piece of code into Swift code.

Objective-C:

#import "SUCacheItem.h"

#define SUCACHEITEM_TOKEN_KEY @"token"
#define SUCACHEITEM_PROFILE_KEY @"profile"

@implementation SUCacheItem

+ (BOOL)supportsSecureCoding
{
return YES;
}

- (id)initWithCoder:(NSCoder *)aDecoder
{
SUCacheItem *item = [[SUCacheItem alloc] init];
item.profile = [aDecoder decodeObjectOfClass:[FBSDKProfile class]   forKey:SUCACHEITEM_PROFILE_KEY];
item.token = [aDecoder decodeObjectOfClass:[FBSDKAccessToken class] forKey:SUCACHEITEM_TOKEN_KEY];
return item;
}

- (void)encodeWithCoder:(NSCoder *)aCoder
{
[aCoder encodeObject:self.profile forKey:SUCACHEITEM_PROFILE_KEY];
[aCoder encodeObject:self.token forKey:SUCACHEITEM_TOKEN_KEY];
}

@end

I translated this piece of code into this:

class CacheItem: NSObject, NSSecureCoding {

let CACHEITEM_TOKEN_KEY = "token"
let CACHEITEM_PROFILE_KEY = "profile"
var profile: AnyObject
var token: AnyObject

func supportsSecureCoding() -> Bool {
    return true
}

required init(coder aDecoder: NSCoder) {
    var item = CacheItem(coder: aDecoder)
    item.profile = aDecoder.decodeObjectOfClass(FBSDKProfile.self, forKey: CACHEITEM_PROFILE_KEY)!
    item.token = aDecoder.decodeObjectOfClass(FBSDKAccessToken.self, forKey: CACHEITEM_TOKEN_KEY)!
}


func encodeWithCoder(aCoder: NSCoder) {
    aCoder.encodeObject(self.profile, forKey: CACHEITEM_PROFILE_KEY)
    aCoder.encodeObject(self.token, forKey: CACHEITEM_TOKEN_KEY)
}   
}

This is giving me an error: Type 'CacheItem' does not conform to protocol 'NSSecureCoding'

What am I missing here?

Thanks in advance!


Solution

  • The supportsSecureCoding function needs to be at the class level:

    class func supportsSecureCoding() -> Bool {
        return true
    }