之前一直是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];
}];
}