惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

S
Secure Thoughts
Security Latest
Security Latest
Simon Willison's Weblog
Simon Willison's Weblog
O
OpenAI News
GbyAI
GbyAI
L
LINUX DO - 最新话题
A
Arctic Wolf
T
Tor Project blog
G
GRAHAM CLULEY
I
InfoQ
博客园_首页
IT之家
IT之家
The Register - Security
The Register - Security
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
P
Proofpoint News Feed
The GitHub Blog
The GitHub Blog
Blog — PlanetScale
Blog — PlanetScale
N
Netflix TechBlog - Medium
K
Kaspersky official blog
博客园 - 三生石上(FineUI控件)
S
SegmentFault 最新的问题
U
Unit 42
PCI Perspectives
PCI Perspectives
量子位
P
Palo Alto Networks Blog
S
Securelist
T
Troy Hunt's Blog
博客园 - 【当耐特】
Recorded Future
Recorded Future
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
S
Security Affairs
Engineering at Meta
Engineering at Meta
T
The Blog of Author Tim Ferriss
博客园 - 聂微东
罗磊的独立博客
N
News and Events Feed by Topic
人人都是产品经理
人人都是产品经理
B
Blog RSS Feed
NISL@THU
NISL@THU
C
Cisco Blogs
T
Threatpost
有赞技术团队
有赞技术团队
Forbes - Security
Forbes - Security
Hugging Face - Blog
Hugging Face - Blog
Last Week in AI
Last Week in AI
T
The Exploit Database - CXSecurity.com
Cloudbric
Cloudbric
Cyberwarzone
Cyberwarzone
Google DeepMind News
Google DeepMind News
C
Cyber Attacks, Cyber Crime and Cyber Security

博客园 - bluce chen

swif debounce实现 oculus quest2的思考 博文阅读密码验证 - 博客园 用户中心 - 博客园 https点对点转发响应示意图 Share架构的一些心得 flutter输入颜色枚举卡顿假死 n2n网络环境搭建 p2p技术之n2n源码核心简单分析一 MIUI通过xposed自动设置root权限 基于xposed实现android注册系统服务,解决跨进程共享数据问题 2017 UICollectionView swift2模版 angularjs 分页精华代码 Reveal分析IOS界面,plist文件读取 php嵌套数组递归搜索返回数组key 结合阿里云服务器,设置家中jetson tk1随时远程登陆 sqlite3 根据实体自动生成建表语句 prism4 StockTrader RI 项目分析一些体会2
分享一个14年写的用户管理类-swift版
bluce chen · 2019-01-03 · via 博客园 - bluce chen

AccountManager类 14年设计,从swift 0.9开始,迭代到现在swift4.0版本,总体几乎没什么改动,简单稳定。

其实现的思路主要还是借助之前net反射的经验,实现了自动保存用户信息本地,同样这个方案也在android上实现了,有想法的同学自己再去实现一般(虽然我这也有,但是就没必要贴出来了,android实现比swift更简单)

话不多说,代码挺简单的,其中依赖SwiftyJSON这个库,相信这个是所有swift项目都会使用的

使用

if(AccountManager.loginStatus){

   print(">>>user aid:\(AccountManager.currentUser!.aid!)")

}
 
import Foundation

/// 登陆获取用于信息通知
let KNotifWithThirdLoginUserInfo = "KNotifWithThirdLoginUserInfo"
let KNotifWithLogout = "KNotifWithLogout"
var _currentUser: UserInfo?
class AccountManager {
    static var loginStatus:Bool{
        get{
            return AccountManager.currentUser != nil
        }
    }

    static func userLogin(_ info:UserInfo?){
         AccountManager.currentUser = info
         NotificationCenter.default.post(name: Notification.Name(rawValue: KNotifWithChangeUser), object:nil)
    }
    
    static func userAutoLogin(){
    
if AccountManager.loginStatus{ KAPIService.requestLoginByToken { (userModel,err) in if(userModel != nil){ if(userModel != nil && userModel?.model?.errcode == 200){ AccountManager.currentUser = userModel?.model?.data.first //可以在这儿通知构建用户登录后的数据库等相关逻辑 }else if(userModel != nil && userModel?.model?.errcode == 100){ AccountManager.userLogout() } } } } } static func userLogout(){ AccountManager.currentUser = nil KUserDefaults.set(nil, forKey: KNotifWithThirdLoginUserInfo) NotificationCenter.default.post(name: Notification.Name(rawValue: KNotifWithChangeUser), object:nil) } class var currentUser: UserInfo? { get { if _currentUser == nil { if let d = KUserDefaults.object(forKey: KNotifWithThirdLoginUserInfo) as? Data { _currentUser = UserInfo(anyObject:"" as AnyObject) do { let json = try JSON(data:d) _currentUser?.initData(json) } catch{} } if let u = _currentUser{ if (u.aid == nil){ _currentUser = nil } } } return _currentUser } set(user) { _currentUser = user if let v = _currentUser{ let data = try! JSONSerialization.data(withJSONObject: v.toDictionary(), options: []) KUserDefaults.set(data, forKey: KNotifWithThirdLoginUserInfo) } else { //MARK: - 在swift3.x开始就不能set nil了,nil并不会删除key //KUserDefaults.set(nil, forKey: KNotifWithThirdLoginUserInfo) KUserDefaults.removeObject(forKey: KNotifWithThirdLoginUserInfo) } KUserDefaults.synchronize() } } class func EnableCurrentUserDebugMode(){ // #if DEBUG // AccountManager.currentUser = UserInfo(JSON: "") // AccountManager.currentUser!.id = 1 // AccountManager.currentUser!.name = "测试用户" // AccountManager.currentUser!.vip = 0 // AccountManager.currentUser!.avatar = "" // if let v = "\(NSDate().timeIntervalSince1970)".toInt(){ // AccountManager.currentUser!.expire = v // } // AccountManager.currentUser!.email = "" // #endif } }

//
//  KCacheModel.swift
//

import Foundation

class KCacheModel:NSObject,KResponseItemSerializable{
    required init(anyObject: AnyObject) {
        super.init()
    }
    
    func converAnyToNSValue(_ anyValue:Any) -> NSObject? {
        switch(anyValue) {
        case let intValue as Int:
            return NSNumber(value: CInt(intValue) as Int32)
        case let doubleValue as Double:
            return NSNumber(value: CDouble(doubleValue) as Double)
        case let stringValue as String:
            return stringValue as NSString
        case let boolValue as Bool:
            return NSNumber(value: boolValue as Bool)
        case let primitiveArrayValue as Array<String>:
            return primitiveArrayValue as NSArray
        case let primitiveArrayValue as Array<Int>:
            return primitiveArrayValue as NSArray
        default:
            return NSNull()
        }
    }
    
    //对象转字典
    func toDictionary()-> NSMutableDictionary{
        let modelDictionary:NSMutableDictionary = NSMutableDictionary()
        let aMirror = Mirror(reflecting: self)//reflect(self)
        for case let (label?, value) in aMirror.children {
            print("lab:\(label) val:\(value)")
            if let nsValue=converAnyToNSValue(value) {
                modelDictionary.setValue(nsValue, forKey:label)
            }
        }
        return modelDictionary
    }
}

KCacheModel.swift

import Foundation
class UserInfo:KCacheModel{
    required init(anyObject: AnyObject) {
        super.init(anyObject: anyObject)
        let jo = JSON(anyObject)
        self.initData(jo)
    }
    
//    convenience init(_ jo:JSON) {}
    func initData(_ jo:JSON) {
        //从本地读取和从远程读取,存储结构不一样,所以需要定制处理
        if let v = jo["app_token"].string{
            self.token = v
        }else{
            self.token = jo["token"].string
        }
        if let v = jo["app_token_exp"].string{
            self.token_exp = v
        }else{
            self.token_exp = jo["token_exp"].string
        }
        if let v = jo["user_info"]["aid"].string{
            self.aid = v
        }else{
           self.aid = jo["aid"].string
        }
        if let v = jo["user_info"]["name"].string{
            self.name =  v
        }else{
            self.name = jo["name"].string
        }
        if let v = jo["user_info"]["head_img_url"].string{
            self.avatar = v
        }else{
            self.avatar = jo["avatar"].string
        }
    }
    
    var token:String?
    var token_exp:String? //用户名称
    var aid:String?
    var avatar:String? //头像
    var name:String?
}

UserInfo.swift

protocol KResponseItemSerializable {
    init(anyObject:AnyObject)
}

KResponseItemSerializable

最后,记得修改用户的属性记得这么用

AccountManager.currentUser?.name = "新名字"

AccountManager.currentUser = AccountManager.currentUser//这是为了更新缓存