分享一个14年写的用户管理类-swift版

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//这是为了更新缓存

原文地址:https://www.cnblogs.com/wyxy2005/p/10214212.html