Swift中用户登录保存用户token(用归档解档)

我们在用swift开发过程中,涉及到用户登录的情况就会保存我们用户的token,这样做的目的不但能实现保存用户登录状态的目的,有时候我们的请求也会要求传入token。对于这些比较小的数据存储我们一般用归档,解档来完成,下面分享一些我的代码,做用户归档,解档
第一步:创建一个我们用户信息的model集成NSObject,这里要注意的是在Swift中的归档解档我们要实现NSCodeing协议的。我们继续

import UIKit

class JWellUserModel: NSObject,NSCoding {
   let filePath = NSHomeDirectory() + "/Documents/contacts.data"
    var mainUserId: Int?
    var id: Int?
    var key: String?
    var name: String?
    // 解档
    required init?(coder aDecoder: NSCoder) {
        super.init()
        self.mainUserId   = aDecoder.decodeObject(forKey: "mainUserId") as? Int
        self.id           = aDecoder.decodeObject(forKey: "id") as? Int
        self.key          = aDecoder.decodeObject(forKey: "key") as? String
        self.name         = aDecoder.decodeObject(forKey: "name") as? String
    }
    
    // 归档
    func encode(with aCoder: NSCoder) {
        aCoder.encode(self.mainUserId,forKey: "mainUserId")
        aCoder.encode(self.id,forKey: "id")
        aCoder.encode(self.key,forKey: "key")
        aCoder.encode(self.name,forKey: "name")
    }
    
    override init() {
        
    }
 
}

第二步:我们创建了之后就去需要归档的地方(我是在网络请求成功后直接归档的)

//这里我用的HandyJson,出来的时候是一个```json```字符串我转了一下
class JWellLoginNetWorking: NSObject {
    var result = NSDictionary()
    
    lazy var model: (JWellUserModel) = {
        let model = JWellUserModel()
        return model
    }()
    
}
          extension JWellLoginNetWorking{
    func loginNetWorking(userName: String, passWord: String) -> (){
        var parmas: [String: Any] = Dictionary()
        parmas["username"] = userName
        parmas["password"] = passWord
        NetWorkRequest(.login(params: parmas), completion: { (response) -> (Void) in
            let dicData = getDictionaryFromJSONString(jsonString: response)
            self.result = dicData["result"] as! NSDictionary
            self.model.key = (self.result["key"] as! String)
            self.model.name = (self.result["name"] as! String)
            self.model.id = (self.result["id"] as! Int)
            self.model.mainUserId = (self.result["mainUserId"] as! Int)
            
            let data = NSMutableData()
            let archive = NSKeyedArchiver(forWritingWith: data)
            archive.encode(self.model, forKey: "userKey")
            archive.finishEncoding()
            data.write(toFile: self.model.filePath, atomically: true)
            
            let tab = JWellCTabBarController()
            kAppWindow??.rootViewController = tab
            kAppWindow??.makeKeyAndVisible()
            
        }, failed: { (str) -> (Void) in
            
        }) { () -> (Void) in
            
        }
    }
    
 
}

到这里我们就完成了归档的操作我们已经报这些数据存下了接下来
第三步:我们在需要的地方去做解档操作,然后用里面的东西( 我们的项目需要把token当做头去做网络请求的,所以我在网络请求添加头的地方处理了)

 var headers: [String : String]? {
        let model = JWellUserModel()
        var key = ""
        let fileData = NSMutableData(contentsOfFile: model.filePath)
        if fileData != nil {
            let unarchiver = NSKeyedUnarchiver(forReadingWith: fileData! as Data)
            let saveUser = unarchiver.decodeObject(forKey: "userKey") as! JWellUserModel
            unarchiver.finishDecoding()
                if saveUser.key != nil {
                    key = saveUser.key!
            }
        }
                return ["Content-Type":"application/json","Authorization":"Bearer " + key]
    }

就这样,我们的归档解档就好了,主要是做了保存用户登录状态,顺便把token保存下来!!!!!

你可能感兴趣的:(Swift中用户登录保存用户token(用归档解档))