UserDefaults 在 Swift 3 中使用
每个应用程序都需要在 UserDefault 中将应用程序或用户相关的详细信息存储在应用程序中。因此,我们在一个类中创建了整个逻辑,以便更好地管理 UserDefaults。
Swift 3
import Foundation
public struct Session {
fileprivate static let defaults = UserDefaults.standard
enum userValues: String {
case auth_token
case email
case fname
case mobile
case title
case userId
case userType
case OTP
case isApproved
}
//MARK: - Getting here User Details
static func getUserSessionDetails()->[String:AnyObject]? {
let dictionary = defaults.object(forKey: "LoginSession") as? [String:AnyObject]
return dictionary
}
//MARK: - Saving Device Token
static func saveDeviceToken(_ token:String){
guard (gettingDeviceToken() ?? "").isEmpty else {
return
}
defaults.removeObject(forKey: "deviceToken")
defaults.set(token, forKey: "deviceToken")
defaults.synchronize()
}
//MARK: - Getting Token here
static func gettingDeviceToken()->String?{
let token = defaults.object(forKey: "deviceToken") as? String
if token == nil{
return ""
}else{ return token}
}
//MARK: - Setting here User Details
static func setUserSessionDetails(_ dic :[String : AnyObject]){
defaults.removeObject(forKey: "LoginSession")
defaults.set(dic, forKey: "LoginSession")
defaults.synchronize()
}
//MARK:- Removing here all Default Values
static func userSessionLogout(){
//Set Activity
defaults.removeObject(forKey: "LoginSession")
defaults.synchronize()
}
//MARK: - Get value from session here
static func getUserValues(value: userValues) -> String? {
let dic = getUserSessionDetails() ?? [:]
guard let value = dic[value.rawValue] else{
return ""
}
return value as? String
}
}
使用 UserDefaults 类
//Saving user Details
Session.setUserSessionDetails(json ?? [:])
//Retriving user Details
let userId = Session.getUserValues(value: .userId) ?? ""