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//這是為了更新快取