IOS UserModel创建

之前一直是NSDictionary党,拿到服务器数据存储到字典后,哪里用到哪里取值。这么做虽然方便,然后可读性差,尤其一段时间后回头做修改,会很难受。于是学着创建model来管理数据。

用户模型创建了两个类:User和UserModel。
User:
使用NSUserDefaults来保存用户信息,提供一些简单方法,包括保存用户信息,清理用户信息,获取一些指定的数据如头像、名字等,登陆状态的判断。

UserModel:
1.处理数据访问,比如登陆获取用户信息,上传头像;
2.把字典中需要的值转成类的属性来保存。

User.h:

#import <Foundation/Foundation.h>
@class UserModel;
@interface User : NSObject

+ (void)saveProfile:(UserModel *)userModel;
+ (NSString *)getMemberID;

+ (void)updatePhoto:(NSString *)photo;

+ (void)loginOut;
+ (BOOL)isLogin;
@end

User.m


#import "User.h"
#import "UserModel.h"

static NSString *const kMemberID = @"memberID";
static NSString *const kBindMobile = @"bindMobile";
static NSString *const kPhoto = @"photo";
static NSString *const kTrueName = @"trueName";
static NSString *const kSex = @"sex";
static NSString *const kEmail = @"email";
static NSString *const kMemberLevel = @"memberLevel";
@implementation User

+ (void)saveMemberID:(NSString *)memberID andBindMobile:(NSString *)bindMobile andPhoto:(NSString *)photo andTrueName:(NSString *)trueName andSex:(NSString *)sex andEmail:(NSString *)email andMemberLevel:(BOOL)memberLevel{
    
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setObject:memberID forKey:kMemberID];
    [userDefaults setObject:bindMobile forKey:kBindMobile];
    [userDefaults setObject:photo forKey:kPhoto];
    [userDefaults setObject:trueName forKey:kTrueName];
    [userDefaults setObject:sex forKey:kSex];
    [userDefaults setObject:email forKey:kEmail];
    [userDefaults setBool:memberLevel forKey:kMemberLevel];
    
    [userDefaults synchronize];
}

+ (void)saveProfile:(UserModel *)userModel{
    [User saveMemberID:userModel.memberID andBindMobile:userModel.bindMobile andPhoto:userModel.photo andTrueName:userModel.trueName andSex:userModel.sex andEmail:userModel.email andMemberLevel:userModel.memberLevel];
}

+ (NSString *)getMemberID{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    return [userDefaults objectForKey:kMemberID];
}

+ (void)updatePhoto:(NSString *)photo{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setObject:photo forKey:kPhoto];
    [userDefaults synchronize];
}

+ (void)loginOut{
    [User saveMemberID:@"" andBindMobile:@"" andPhoto:@"" andTrueName:@"" andSex:@"" andEmail:@"" andMemberLevel:0];
}

+ (BOOL)isLogin{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSString *memberIDString = [userDefaults objectForKey:kMemberID];
    return memberIDString.length>0;
}
@end

UserModel.h

#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>

@interface UserModel : NSObject
@property (copy, nonatomic) NSString *memberID;
@property (copy, nonatomic) NSString * bindMobile;
@property (copy, nonatomic) NSString *photo;
@property (copy, nonatomic) NSString *trueName;
@property (copy, nonatomic) NSString *sex;
@property (copy, nonatomic) NSString *email;
@property (assign, nonatomic) BOOL memberLevel;


- (void)loginWithParameter:(NSDictionary *)paramter
                   success:(void (^)(NSString *successMessage))success
                   failure:(void (^)(NSString *failureMessage))failure;

- (void)getUserinfoByMemberID:(NSString *)memberID
                      success:(void(^)(NSString *successMsg))success
                      failure:(void(^)(NSString *failureMsg))failure;

- (void)editUserinfoWithParameter:(NSDictionary *)parameter
                          success:(void (^)(NSString *successMsg))success
                          failure:(void (^)(NSString *failureMsg))failure;

- (void)updatePortrait:(UIImage *)portrait
               success:(void (^)(NSString *))success
               failure:(void (^)(NSString *))failure;

@end

UserModel.m

#import "UserModel.h"
#import "AFNetworking.h"
#import "User.h"
#import <objc/runtime.h>
#define WS(weakSelf)  __weak __typeof(&*self)weakSelf = self;

static NSString *const kResult = @"result";
static NSString *const kSuccess = @"success";
static NSString *const kEntity = @"entity";
static NSString *const kMemberID = @"MemberID";
static NSString *const kBindMobile = @"BindMobile";
static NSString *const kPhoto = @"Photo";
static NSString *const kTrueName = @"TrueName";
static NSString *const kSex = @"Sex";
static NSString *const kEmail = @"Email";
static NSString *const kMemberLevel = @"MemberLevel";
static NSString *const kErrorMsg = @"errorMsg";
@implementation UserModel


- (void)loginWithParameter:(NSDictionary *)paramters success:(void (^)(NSString *))success failure:(void (^)(NSString *))failure{
    WS(weakSelf);
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager POST:@"http://musicbox.jidait.com/WebApi/Member/Login" parameters:paramters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        id result = [responseObject objectForKey:kResult];
        
        if ([[result objectForKey:kSuccess] boolValue]) {
            if (success) {
                success(@"登陆成功");
            }
            
            NSDictionary * entity = [responseObject objectForKey:kEntity];
            [weakSelf map:entity];
            [User saveProfile:self];
        }
        else{
            NSString *errorMsg = [NSString stringWithFormat:@"%@",[result objectForKey:kErrorMsg]];
            if (failure) {
                failure(errorMsg);
            }
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) {
            failure([error localizedDescription]);
        }
    }];
}

- (void)getUserinfoByMemberID:(NSString *)memberID success:(void (^)(NSString *))success failure:(void (^)(NSString *))failure{
    WS(weakSelf);
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager POST:@"http://musicbox.jidait.com/WebApi/Member/GetEntity" parameters:@{@"ID":memberID} progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        id result = [responseObject objectForKey:kResult];
        if ([[result objectForKey:kSuccess] boolValue]){
            if (success) {
                success(@"获取成功");
            }

            NSDictionary * entity = [responseObject objectForKey:kEntity];
            [weakSelf map:entity];
        }
        else{
            NSString *errorMsg = [NSString stringWithFormat:@"%@",[result objectForKey:kErrorMsg]];
            failure(errorMsg);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failure([error localizedDescription]);
    }];
    
}

- (void)editUserinfoWithParameter:(NSDictionary *)parameter success:(void (^)(NSString *))success failure:(void (^)(NSString *))failure{
    WS(weakSelf);
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager POST:@"http://musicbox.jidait.com/WebApi/Member/Edit" parameters:parameter progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        id result = [responseObject objectForKey:kResult];
        if ([[result objectForKey:kSuccess] boolValue]) {
            if(success){
                success(@"修改成功");
            }
            
            NSDictionary * entity = [responseObject objectForKey:kEntity];
            [weakSelf map:entity];
        }
        else{
            if (failure) {
                NSString *errorMsg = [NSString stringWithFormat:@"%@",[result objectForKey:kErrorMsg]];
                failure(errorMsg);
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) {
            failure([error localizedDescription]);
        }
    }];
}

- (void)updatePortrait:(UIImage *)portrait success:(void (^)(NSString *))success failure:(void (^)(NSString *))failure{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager POST:@"http://musicbox.jidait.com/WebApi/Member/UploadPhoto" parameters:@{@"ID":[User getMemberID]} constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        [formData appendPartWithFileData:[self compressImage:portrait] name:@"Photo" fileName:@"img.jpg" mimeType:@"image/jpeg"];
    } progress:nil
          success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
              id result = [responseObject objectForKey:kResult];
              if ([[result objectForKey:kSuccess] boolValue]){
                  if (success) {
                      success(@"提交成功");
                  }
                  
                  [User updatePhoto:[NSString stringWithFormat:@"http://musicbox.jidait.com%@",[result objectForKey:@"errorMsg"]]];
              }
              else{
                  NSString *errorMsg = [NSString stringWithFormat:@"%@",[result objectForKey:kErrorMsg]];
                  if (failure) {
                      failure(errorMsg);
                  }
              }
        
    }
          failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
              if (failure) {
                  failure([error localizedDescription]);
              }
    }];
}

- (void)map:(NSDictionary *)entity{
    
    self.memberID = [self filtereDictionary:entity ForKey:kMemberID]?:@"";
    self.bindMobile = [self filtereDictionary:entity ForKey:kBindMobile]?:@"";
    self.photo = [self filtereDictionary:entity ForKey:kPhoto]?:@"";
    self.trueName = [self filtereDictionary:entity ForKey:kTrueName]?:@"";
    self.sex = [self filtereDictionary:entity ForKey:kSex]?:@"";
    self.email = [self filtereDictionary:entity ForKey:kEmail]?:@"";
    self.memberLevel = [[self filtereDictionary:entity ForKey:kMemberLevel]?:@0 boolValue];
}


/*处理三种情况:
 1.json中对应key不存在,那么程序抛出异常。
 2.key对应的值为[NSNull null],那么返回nil;
*/
- (id)filtereDictionary:(NSDictionary *)entity ForKey:(NSString *)key{
    id value = [entity objectForKey:key];
    if (!value) {
        NSException *exception = [NSException exceptionWithName:@"警告" reason:@"字典中没有对应的Key" userInfo:nil];
        @throw exception;
    }
    if ([value isEqual:[NSNull null]]) {
            return nil;
    }
    return value;
}

//其他
- (NSData *)compressImage:(UIImage *)image
{
    CGSize size = [self scaleSize:image.size];
    UIGraphicsBeginImageContext(size);
    [image drawInRect:CGRectMake(0, 0, size.width, size.height)];
    UIImage * scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    NSUInteger maxFileSize = 500 * 1024;
    CGFloat compressionRatio = 0.7f;
    CGFloat maxCompressionRatio = 0.1f;
    
    NSData *imageData = UIImageJPEGRepresentation(scaledImage, compressionRatio);
    
    while (imageData.length > maxFileSize && compressionRatio > maxCompressionRatio) {
        compressionRatio -= 0.1f;
        imageData = UIImageJPEGRepresentation(image, compressionRatio);
    }
    
    return imageData;
}

- (CGSize)scaleSize:(CGSize)sourceSize
{
    float width = sourceSize.width;
    float height = sourceSize.height;
    if (width >= height) {
        return CGSizeMake(800, 800 * height / width);
    } else {
        return CGSizeMake(800 * width / height, 800);
    }
}

@end

举个例子,我现在要作登陆操作:
LoginViewController.m

- (void)doRightButtonAction{
    MBProgressHUD *HUD = [[MBProgressHUD alloc] initWithView:self.view];
    HUD.labelText = @"正在登陆";
    [HUD show:YES];
    [self.view addSubview:HUD];
    
    self.loginModel = [UserModel new];
    NSDictionary *parameter = @{@"mobile":@"18758363317",@"password":@"111111"};
    [self.loginModel loginWithParameter:parameter success:^(NSString *successMessage) {
        HUD.mode = MBProgressHUDModeText;
        HUD.labelText = successMessage;
        [HUD hide:YES afterDelay:1.5];
    } failure:^(NSString *failureMessage) {
        HUD.mode = MBProgressHUDModeText;
        HUD.labelText = failureMessage;
        [HUD hide:YES afterDelay:1.5];
    }];
    
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 201,312评论 5 473
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 84,578评论 2 377
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 148,337评论 0 333
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,134评论 1 272
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,161评论 5 363
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,303评论 1 280
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,761评论 3 393
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,421评论 0 256
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,609评论 1 295
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,450评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,504评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,194评论 3 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,760评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,836评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,066评论 1 257
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,612评论 2 348
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,178评论 2 341

推荐阅读更多精彩内容