分享一个14年写的用户管理类-swift版
2024-08-30 10:25:30
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 == ){
AccountManager.currentUser = userModel?.model?.data.first
//可以在这儿通知构建用户登录后的数据库等相关逻辑
}else if(userModel != nil && userModel?.model?.errcode == ){
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//这是为了更新缓存
最新文章
- [Delphi] Delphi版本号对照
- 拥抱.NET Core,学习.NET Core的基础知识补遗
- DevOps的修炼之路!
- IE浏览器打开f12才正常
- 【Android学习日记】
- tornado 信号处理
- 跟我一起学习ASP.NET 4.5 MVC4.0(一)(转)
- jsonp实现跨域请求
- [C++] 对象地址与接口指针的故事
- 不一样的味道--Html和Xml解析、格式、遍历
- Python Redis 数据复制.
- DFS - leetcode [深度优先遍历]
- ejabberd聊天室离线消息
- 【算法】RMQ LCA 讲课杂记
- virsh命令来创建虚拟机
- golang range遍历是新创建对象还是创建对象的引用
- C++简单交换堆排序的代码
- [模板] dp套dp &;&; bzoj5336: [TJOI2018]party
- 4-18 class与id的区别
- ionic2中使用moment.js
热门文章
- 05 JS基础DOM
- HU-1043
- python3 写excel文件 xlsxwriter模块
- idea中git常见使用场景
- 文本建模、文本分类相关开源项目推荐(Pytorch实现)
- MAC vim安装gruvbox主题
- PeopleSoft通过status汇总进程运行情况
- H5-处理支付-前端部分
- ASP.NET Easyui datagrid增删改+sqlhelper
- 【JDBC】java.sql.SQLException: The server time zone value &#39;&#214;&#208;&#185;&#250;&#177;&#234;&#215;&#188;&#202;&#177;&#188;&#228;&#39; is unrecognized or represents more than one time zone.