zoukankan      html  css  js  c++  java
  • 归档 & 解档

    代码实现

    遵守协议

    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
  • 相关阅读:
    课后总结
    构建之法阅读笔记01
    软件工程周总结02
    开课博客
    二维数组最大子数组和
    大二下周总结四
    大二下周总结三
    定义一个整型数组,返回该数组中子数组和的最大值
    软件工程开课
    定义一个数组返回最大子数组的值(1)
  • 原文地址:https://www.cnblogs.com/Milo-CTO/p/4654717.html
Copyright © 2011-2022 走看看