单例存储账号

返回doc路径

#import "NSString+DocumentPath.h"

@implementation NSString (DocumentPath)

+(NSString *)fileDocumentsPathWith:(NSString *)name{
    NSString *documents = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
    
    NSString *filePath = [documents stringByAppendingPathComponent:name];
    return filePath;
}
#import "AccountInfo.h"
#import "NSString+DocumentPath.h"

#define kAccountFileName @"accountInfo"

@implementation AccountInfo

+(instancetype)currentAccount{
    static AccountInfo *account;
    
    //代码只执行一次
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        NSString *filePath = [NSString fileDocumentsPathWith:kAccountFileName];
        account  = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
        if (!account) {
            account = [[AccountInfo alloc] init];
        }
    })
    return account;
}

//存储信息,
-(void)saveLoginInfo:(NSDictionary *)info{ //1.保存 token self.accessToken = info[@"access_token"]; self.uid = info[@"uid"]; //当前时间 NSDate *date = [NSDate date]; //生命周期 NSNumber *expires = info[@"expires_in"]; //有效的截止时间 self.expiresIn = [date dateByAddingTimeInterval:expires.floatValue]; //归档登录信息 [NSKeyedArchiver archiveRootObject:self toFile:[NSString fileDocumentsPathWith:kAccountFileName]]; } -(BOOL)isLogin{ //比较有效截止时间跟当前时间 NSComparisonResult result = [self.expiresIn compare:[NSDate date]]; if (self.accessToken && result > 0) { return YES; } return NO; } -(BOOL)logout{ self.accessToken = nil; self.uid = nil; self.expiresIn = nil; //删除归档文件 NSFileManager *manager = [NSFileManager defaultManager]; //文件路径 NSString *filePath = [NSString fileDocumentsPathWith:kAccountFileName]; //删除归档的登录信息 [manager removeItemAtPath:filePath error:nil]; return YES; }
//返回固定的网络参数
-(NSMutableDictionary *)requetsParams{ if ([self isLogin]) { return [NSMutableDictionary dictionaryWithObject:self.accessToken forKey:@"access_token"]; } return nil; } #pragma mark coding 代理 -(id)initWithCoder:(NSCoder *)aDecoder{ self = [super init]; if (self) { self.accessToken = [aDecoder decodeObjectForKey:@"access_token"]; self.expiresIn = [aDecoder decodeObjectForKey:@"expires_in"]; self.uid = [aDecoder decodeObjectForKey:@"uid"]; } return self; } - (void)encodeWithCoder:(NSCoder *)coder { //保存对象的属性 [coder encodeObject:self.accessToken forKey:@"access_token"]; [coder encodeObject:self.expiresIn forKey:@"expires_in"]; [coder encodeObject:self.uid forKey:@"uid"]; }
原文地址:https://www.cnblogs.com/10-19-92/p/4955812.html