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
  • 相关阅读:
    常见局域网类别
    精确率,召回率,准确率
    create-react-app创建第一个react程序_windows8.1
    编码与解码
    深度学习---嵌套简记
    反向传播算法简记
    MarkDown语法简记
    Vscode中的配置文件的作用简述
    wireshark 更好的查看TCP协议的数据,跟踪tcp流程
    wireshark 基础,颜色规则,过滤条件使用与多条过滤
  • 原文地址:https://www.cnblogs.com/Milo-CTO/p/4654717.html
Copyright © 2011-2022 走看看