代码实现
遵守协议
class AccessToken: NSObject, NSCoding
实现协议方法
// MARK: - 归档&解档
required init(coder aDecoder: NSCoder) {
access_token = aDecoder.decodeObjectForKey("access_token") as! String
expires_in = aDecoder.decodeDoubleForKey("expires_in") as NSTimeInterval
expiresDate = aDecoder.decodeObjectForKey("expiresDate") as? NSDate
uid = aDecoder.decodeIntegerForKey("uid") as Int
}
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(access_token, forKey: "access_token")
aCoder.encodeDouble(expires_in, forKey: "expires_in")
aCoder.encodeObject(expiresDate, forKey: "expiresDate")
aCoder.encodeInteger(uid, forKey: "uid")
}
保存和加载账户信息
/// 归档路径
static let archivePath = (NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last as! String).stringByAppendingPathComponent("account.plist")
- 保存账户信息
NSKeyedArchiver.archiveRootObject(account, toFile: UserAccount.archivePath)
- 加载账户信息
/// 加载账户信息
///
/// :returns: 如果过期返回 nil
class func loadUserAccount() -> UserAccount? {
if let account = NSKeyedUnarchiver.unarchiveObjectWithFile(archivePath) as? UserAccount {
// 判断是否过期
if account.expiresDate!.compare(NSDate()) == NSComparisonResult.OrderedDescending {
return account
}
}
return nil
}
测试加载用户账户
- 在 AppDelegate 中增加如下代码
/// 全局用户账户
var sharedUserAccount = UserAccount.loadUserAccount()
由于后续所有网络访问都基于用户账户中的
access_token
,因此在AppDelegate
中定义一个全局变量,从而避免重复加载
修改 BaseTableViewController 中的用户是否登录判断
/// 用户登录标记
var userLogin = sharedUserAccount != nil