标签:
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
}
/// 全局用户账户
var sharedUserAccount = UserAccount.loadUserAccount()
由于后续所有网络访问都基于用户账户中的
access_token
,因此在AppDelegate
中定义一个全局变量,从而避免重复加载
/// 用户登录标记
var userLogin = sharedUserAccount != nil
标签:
原文地址:http://www.cnblogs.com/Milo-CTO/p/4654717.html